//
//  SheetListView.swift
//  歌单列表View
//  主要用来收藏歌曲的时候选择歌单
//
//  Created by smile on 2019/4/27.
//  Copyright © 2019 ixuea. All rights reserved.
//

import UIKit

//导入响应式编程框架
import RxSwift

class SheetListView: BaseView {
    @IBOutlet weak var tableView: UITableView!
    
    var contentView:UIView!
    
    var dataArray:[Sheet]=[]
    
    /// 歌单点击回调方法
    var onSheetClick:((_ data:Sheet) -> Void)!
    
    //负责对象销毁
    //这个功能类似NotificationCenter的removeObserver
    let disposeBag = DisposeBag()
    
    override func initViews() {
        super.initViews()
        
        contentView = Bundle.main.loadNibNamed("SheetListView", owner: self, options: nil)!.first as! UIView
        
        self.addSubview(contentView)
        
        
        //歌单Cell
        tableView.register(UINib(nibName: TopicCell.NAME, bundle: nil), forCellReuseIdentifier: TopicCell.NAME)
        
    }
    
    override func initDatas() {
        super.initDatas()
        fetchData()
    }
    
    func fetchData() {
        //获取创建的歌单
        Api.shared
            .createSheets(PreferenceUtil.userId()!)
            .subscribeOnSuccess { (data) in
                if let data = data?.data {
                    self.dataArray=self.dataArray+data
                    
                    self.tableView.reloadData()
                }
        }.disposed(by: disposeBag)
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //设置添加的View的frame
        contentView.frame = bounds
    }
}

extension SheetListView: UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell=tableView.dequeueReusableCell(withIdentifier: TopicCell.NAME) as! TopicCell
        
        let data = dataArray[indexPath.row]
       
        cell.bindData(data)
        
        return cell
    }
    
    /// Item点击事件
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - indexPath: <#indexPath description#>
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        print("SheetListView didSelectRowAt:\(indexPath.row)")
        
        //取出数据
        let data = dataArray[indexPath.row]
        
        onSheetClick(data)
    }
}
